package com.cloud.rou.im.client.msg;

import com.cloud.rou.im.client.context.UserContextHolder;
import com.cloud.rou.im.core.util.SingletonUtil;
import com.cloud.rou.im.msg.Msg;
import com.cloud.rou.im.client.statemachine.StateMachineContext;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.*;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class ChatMessageQueueExecutor {
/*    private final ChannelHandlerContext ctx;*/

    private final BlockingQueue<StateMachineContext> queue;

    private final ExecutorService mainExecutor;

    private Map<Long,StateMachineContext> maps;

    private ChatMessageQueueExecutor() {
        queue = new LinkedBlockingQueue<>();
     /*   ctx = UserContextHolder.context();*/
        maps = new ConcurrentHashMap<>();
        this.mainExecutor = Executors.newFixedThreadPool(1, r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            thread.setName("com.cloud.rou.im.client.msg.MessageQueueExecutor");
            return thread;
        });

       start();
    }
    public static ChatMessageQueueExecutor instance(){
        return SingletonUtil.get(ChatMessageQueueExecutor.class);
    }
    class MainWork implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    System.out.println("123");
                    StateMachineContext context = queue.take();
                    Msg msg1 = context.getMsg();
                    if (msg1.getMsgId()==1L){
                        System.out.println("发送成功");
                        maps.put(msg1.getMsgId(),context);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
   /*     @Override
        public void run() {
            while (true) {
                try {
                    StateMachineContext context = queue.take();
                    Msg msg1 = context.getMsg();
                    ChannelFuture channelFuture = ctx.writeAndFlush(DataPacketFactory.getPacket(msg1));
                    channelFuture.addListener(future -> {
                        StateMachine stateMachine = context.getStateMachine();
                        if (!future.isSuccess()) {
                            stateMachine.fire(MsgEvent.ERROR);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }*/
    }
    public void start() {
        mainExecutor.submit(new MainWork());
    }
    public void add(StateMachineContext context) {
        queue.offer(context);
    }
}

